from PyQt6.QtCore import QThread, pyqtSignal
from ai_models import OpenAIResponse

class AIResponseThread(QThread):
    response_ready = pyqtSignal(OpenAIResponse)

    def __init__(self, openai_chat, message, model_name, history=None):
        super().__init__()
        self.openai_chat = openai_chat
        self.message = message
        self.model_name = model_name
        self.history = history or []
        
    def run(self):
        try:
            accumulated_text = ""
            buffer = ""  # 用于积累字符
            buffer_size = 10  # 每积累10个字符发送一次
            
            for chunk in self.openai_chat.generate_response(self.model_name, self.message, self.history):
                if hasattr(chunk, 'choices') and chunk.choices:
                    chunk_text = chunk.choices[0].delta.content or ""
                    accumulated_text += chunk_text
                    buffer += chunk_text
                    
                    # 当缓冲区达到一定大小或遇到特殊字符时发送
                    if (len(buffer) >= buffer_size or 
                        '\n' in buffer or 
                        '。' in buffer or 
                        '!' in buffer or 
                        '?' in buffer or
                        '！' in buffer or
                        '？' in buffer):
                        self.response_ready.emit(
                            self.openai_chat.create_response(buffer, is_final=False)
                        )
                        buffer = ""  # 清空缓冲区
            
            # 发送剩余的缓冲区内容
            if buffer:
                self.response_ready.emit(
                    self.openai_chat.create_response(buffer, is_final=False)
                )
            
            # 最后发送完整的渲染后文本
            formatted_text = self.openai_chat.format_final_response(accumulated_text)
            self.response_ready.emit(
                self.openai_chat.create_response(formatted_text, is_final=True)
            )
            
        except Exception as e:
            self.response_ready.emit(
                self.openai_chat.create_response(error=f"错误: {str(e)}", is_final=True)
            )